package com.bestcem.xm.user.service.impl;

import cn.hutool.core.lang.ObjectId;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bestcem.xm.common.core.constant.AppRequestErrorCode;
import com.bestcem.xm.common.core.constant.AppResourceErrorCode;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.enums.AuthErrorCodeEnum;
import com.bestcem.xm.common.core.enums.ReqErrorCodeEnum;
import com.bestcem.xm.common.core.enums.ResourceErrorCodeEnum;
import com.bestcem.xm.user.dao.UserAccountDao;
import com.bestcem.xm.user.entity.pojo.UserConditionGroupDO;
import com.bestcem.xm.user.enums.UserAuthLogOpTypeEnum;
import com.bestcem.xm.user.enums.UserEditionEnum;
import com.bestcem.xm.user.enums.UserStatusEnum;
import com.bestcem.xm.user.grpc.client.PackageGrpcService;
import com.bestcem.xm.user.grpc.client.dto.PackageDTO;
import com.bestcem.xm.user.service.*;
import com.bestcem.xm.user.service.dto.group.UserConditionGroupDTO;
import com.bestcem.xm.user.service.dto.role.RolePermissionDTO;
import com.bestcem.xm.user.service.dto.role.UserRoleDTO;
import com.bestcem.xm.user.service.dto.user.*;
import com.bestcem.xm.user.service.third.GrowingIOService;
import com.bestcem.xm.user.util.business.PwdUtil;
import com.bestcem.xm.user.util.business.UserLockUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户业务Service
 *
 * @author wangyunyun <yunyun.wang@idiaoyan.com>
 * @version v1.0
 * @date 2022/3/16 11:07
 */
@Slf4j
@Service
public class UserBusinessServiceImpl implements UserBusinessService {

    @Autowired
    private RoleService roleService;

    @Resource
    private UserLockUtil userLockUtil;

    @Autowired
    private UserUserRoleService userUserRoleService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserUserAuthLogService userUserAuthLogService;

    @Autowired
    private RolePermissionService rolePermissionService;

    @Autowired
    private GrowingIOService growingIOService;

    @Autowired
    private PackageGrpcService packageGrpcService;

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private UserAccountDao userAccountDao;

    @Override
    public ServiceResult<UserDTO> getAdminUserByOrgId(String orgId) {
        // 获取系统管理员角色id
        ServiceResult<String> roleRt = roleService.getAdminRole(orgId);
        if (!roleRt.isSuccess()) {
            return ServiceResult.fail(null, roleRt.getMsg(), roleRt.getErrorCode());
        }
        String adminRoleId = roleRt.getData();
        if (StringUtils.isBlank(adminRoleId)) {
            return ServiceResult.success();
        }

        // 通过系统管理员角色id查询用户信息
        List<UserDTO> userDTOS = this.listUserByRoleId(adminRoleId, orgId).getData();
        if (CollectionUtils.isEmpty(userDTOS)) {
            return ServiceResult.success();
        }

        return ServiceResult.success(userDTOS.get(0));
    }

    @Override
    public ServiceResult<List<UserDTO>> getSeniorAdminByOrgId(String orgId) {
        // 获取高级管理员角色id
        ServiceResult<String> roleRt = roleService.getSeniorAdminRole(orgId);
        if (!roleRt.isSuccess()) {
            return ServiceResult.fail(null, roleRt.getMsg(), roleRt.getErrorCode());
        }
        String roleId = roleRt.getData();
        if (StringUtils.isBlank(roleId)) {
            return ServiceResult.success();
        }

        // 通过高级管理员角色id查询用户信息
        List<UserDTO> userDTOS = this.listUserByRoleId(roleId, orgId).getData();
        if (CollectionUtils.isEmpty(userDTOS)) {
            return ServiceResult.success();
        }
        return ServiceResult.success(userDTOS);
    }

    @Override
    public ServiceResult<List<UserDTO>> getDeliverCheckUserByOrgId(String orgId) {
        // 获取投放审核角色id
        ServiceResult<String> roleRt = roleService.getDeliverCheckRole(orgId);
        if (!roleRt.isSuccess()) {
            return ServiceResult.fail(null, roleRt.getMsg(), roleRt.getErrorCode());
        }
        String roleId = roleRt.getData();
        if (StringUtils.isBlank(roleId)) {
            return ServiceResult.success();
        }

        // 通过投放审核角色id查询用户信息
        List<UserDTO> userDTOS = this.listUserByRoleId(roleId, orgId).getData();
        if (CollectionUtils.isEmpty(userDTOS)) {
            return ServiceResult.success();
        }
        return ServiceResult.success(userDTOS);
    }

    @Override
    public ServiceResult<Boolean> hasRole(String userId, String orgId, String roleId) {
        // 校验参数
        if (StringUtils.isBlank(userId) || StringUtils.isBlank(orgId) || StringUtils.isBlank(roleId)) {
            return ServiceResult.fail("参数不能为空");
        }
        // 获取用户的角色列表
        UserUserRoleDTO userUserRoleDTO = new UserUserRoleDTO();
        userUserRoleDTO.setUserId(userId);
        userUserRoleDTO.setOrgId(orgId);
        userUserRoleDTO.setRoleId(roleId);
        List<UserUserRoleDTO> userRoleDTOS = userUserRoleService.listByCondition(userUserRoleDTO).getData();
        return ServiceResult.success(CollectionUtils.isNotEmpty(userRoleDTOS));
    }

    @Override
    public ServiceResult<Integer> checkSuper(String userId, String orgId) {
        // 校验参数
        ServiceResult<String> checkParamRt = checkParamByCheckRole(userId, orgId);
        if (!checkParamRt.isSuccess()) {
            ServiceResult<Integer> failRt = ServiceResult.fail(checkParamRt.getMsg());
            failRt.setErrorCode(checkParamRt.getErrorCode());
            return failRt;
        }
        orgId = checkParamRt.getData();

        // 获取系统管理员角色id
        String adminRoleId = roleService.getAdminRole(orgId).getData();
        // 判断用户是否有系统管理员角色
        ServiceResult<Boolean> hasRoleRt = this.hasRole(userId, orgId, adminRoleId);

        return hasRoleRt.getData() != null && hasRoleRt.getData()
                ? ServiceResult.success(NumberUtils.INTEGER_ONE) : ServiceResult.success(NumberUtils.INTEGER_ZERO);
    }

    @Override
    public ServiceResult<Integer> checkSenior(String userId, String orgId) {
        // 校验参数
        ServiceResult<String> checkParamRt = checkParamByCheckRole(userId, orgId);
        if (!checkParamRt.isSuccess()) {
            ServiceResult<Integer> failRt = ServiceResult.fail(checkParamRt.getMsg());
            failRt.setErrorCode(checkParamRt.getErrorCode());
            return failRt;
        }
        orgId = checkParamRt.getData();

        // 获取高级管理员角色id
        String seniorAdminRoleId = roleService.getSeniorAdminRole(orgId).getData();
        // 判断用户是否有高级管理员角色
        ServiceResult<Boolean> hasRoleRt = this.hasRole(userId, orgId, seniorAdminRoleId);

        return hasRoleRt.getData() != null && hasRoleRt.getData()
                ? ServiceResult.success(NumberUtils.INTEGER_ONE) : ServiceResult.success(NumberUtils.INTEGER_ZERO);
    }

    @Override
    public ServiceResult<String> createUserAuthLog(UserDTO userDTO, String ipAddress) {
        // 增加登录日志
        UserAuthLogDTO userAuthLogDTO = new UserAuthLogDTO();
        userAuthLogDTO.setOrgId(userDTO.getOrgId());
        userAuthLogDTO.setUserId(userDTO.getUserId());
        userAuthLogDTO.setOpIp(ipAddress);
        userAuthLogDTO.setOpType(UserAuthLogOpTypeEnum.LOGIN.getType());
        userAuthLogDTO.setCreateTime(userDTO.getUpdateTime());
        userAuthLogDTO.setUpdateTime(userDTO.getUpdateTime());
        userAuthLogDTO.setCreatorId(userDTO.getUserId());
        userAuthLogDTO.setOperatorId(userDTO.getUserId());
        return userUserAuthLogService.insert(userAuthLogDTO);
    }

    @Override
    public ServiceResult<Void> updateUserLastLoginTime(UserDTO userDTO, String ipAddress) {
        // 更新用户登录时间
        UserDTO updateUser = new UserDTO();
        updateUser.setUserId(userDTO.getUserId());
        updateUser.setLastLoginTime(userDTO.getUpdateTime());
        updateUser.setUpdateTime(userDTO.getUpdateTime());
        userService.updateById(updateUser);

        // 增加登录日志
        this.createUserAuthLog(userDTO, ipAddress);
        return ServiceResult.success();
    }

    @Override
    public ServiceResult<List<UserDTO>> listUserByRoleId(String roleId, String orgId) {
        // 校验参数
        if (StringUtils.isBlank(roleId) || StringUtils.isBlank(orgId)) {
            return ServiceResult.fail("参数为空");
        }

        // 通过系统管理员角色id查询用户与角色的关联关系
        UserUserRoleDTO userUserRoleDTO = new UserUserRoleDTO();
        userUserRoleDTO.setRoleId(roleId);
        userUserRoleDTO.setOrgId(orgId);
        List<UserUserRoleDTO> userRoleDTOS = userUserRoleService.listByCondition(userUserRoleDTO).getData();
        if (CollectionUtils.isEmpty(userRoleDTOS)) {
            return ServiceResult.success();
        }

        // 通过用户id集合查询用户
        List<String> userIds = userRoleDTOS.stream().map(UserUserRoleDTO::getUserId).distinct().collect(Collectors.toList());
        return ServiceResult.success(userService.selectByIds(userIds).getData());
    }

    @Override
    public ServiceResult<Map<String, Set<String>>> listUserPermissions(String userId, String orgId) {
        // 校验参数
        if (StringUtils.isBlank(userId) || StringUtils.isBlank(orgId)) {
            return ServiceResult.fail("参数不能为空");
        }

        // 设置返回值: 用户权限
        Map<String, Set<String>> userPerms = new HashMap<>();

        // 查询当前用户所拥有的角色id列表
        UserUserRoleDTO userUserRoleDTO = new UserUserRoleDTO();
        userUserRoleDTO.setUserId(userId);
        List<UserUserRoleDTO> userRoles = userUserRoleService.listByCondition(userUserRoleDTO).getData();
        if (CollectionUtils.isEmpty(userRoles)) {
            return ServiceResult.success(userPerms);
        }

        // 查询角色权限
        List<String> roleIds = userRoles.stream().map(UserUserRoleDTO::getRoleId).distinct().collect(Collectors.toList());
        List<RolePermissionDTO> rolePerms = rolePermissionService.listByRoleIds(roleIds, orgId).getData();
        if (CollectionUtils.isEmpty(rolePerms)) {
            return ServiceResult.success(userPerms);
        }

        // 遍历角色权限, 设置用户权限
        for (RolePermissionDTO rolePerm : rolePerms) {
            JSONObject perm = JSON.parseObject(rolePerm.getPermission());
            Set<String> moduleNames = perm != null ? perm.keySet() : null;
            if (CollectionUtils.isEmpty(moduleNames)) {
                continue;
            }
            // 遍历角色模块权限
            for (String moduleName : moduleNames) {
                Set<String> modulePerms = CollectionUtils.isNotEmpty(userPerms.get(moduleName)) ? userPerms.get(moduleName) : new HashSet<>();
                List<String> perms = JSON.parseArray(JSON.toJSONString(perm.get(moduleName)), String.class);
                modulePerms.addAll(perms);

                userPerms.put(moduleName, modulePerms);
            }
        }

        return ServiceResult.success(userPerms);
    }

    @Override
    public ServiceResult<Map<String, Map<String, Set<String>>>> listUserPermissionsV2(String userId, String orgId) {
        // 查询权限
        ServiceResult<Map<String, Set<String>>> result = this.listUserPermissions(userId, orgId);
        if (!result.isSuccess()) {
            return ServiceResult.fail(result.getMsg());
        }

        // 封装参数
        Map<String, Map<String, Set<String>>> modPerms = new HashMap<>();
        if (result.getData() != null && result.getData().size() > 0) {
            for (Map.Entry<String, Set<String>> entry : result.getData().entrySet()) {
                String[] moduleAndRes = entry.getKey().split("_");
                String mod = moduleAndRes[0];
                String res = moduleAndRes[1];
                Map<String, Set<String>> modPerm = modPerms.computeIfAbsent(mod, k -> new HashMap<>());
                modPerm.put(res, entry.getValue());
            }
        }
        return ServiceResult.success(modPerms);
    }

    @Override
    public ServiceResult<List<UserDTO>> listDeliverCheckerUsers(String orgId) {
        // 获取投放审核角色id
        ServiceResult<String> getDeliverCheckRoleRt = roleService.getDeliverCheckRole(orgId);
        if (!getDeliverCheckRoleRt.isSuccess()) {
            ServiceResult<List<UserDTO>> failRt = ServiceResult.fail(getDeliverCheckRoleRt.getMsg());
            return failRt.setErrorCode(getDeliverCheckRoleRt.getErrorCode());
        }

        // 不存在投放审核角色则创建系统内置的投放审核角色和对应的权限
        if (StringUtils.isBlank(getDeliverCheckRoleRt.getData())) {
            ServiceResult<UserRoleDTO> createDeliverCheckRoleRt = roleService.createDeliverCheckRole(orgId);
            if (!createDeliverCheckRoleRt.isSuccess()) {
                ServiceResult<List<UserDTO>> failRt = ServiceResult.fail(createDeliverCheckRoleRt.getMsg());
                return failRt.setErrorCode(createDeliverCheckRoleRt.getErrorCode());
            }
            // 返回结果
            return this.listUserByRoleId(createDeliverCheckRoleRt.getData().getRoleId(), orgId);
        } else {
            // 获取拥有投放审核角色的用户，并返回结果
            return this.listUserByRoleId(getDeliverCheckRoleRt.getData(), orgId);
        }
    }

    @Override
    public ServiceResult<Void> uploadGrowingio(OrganizationDTO organizationDTO, PackageDTO packageDTO) {
        UserDTO userDTO = new UserDTO();
        userDTO.setStatus(UserStatusEnum.ACTIVATED.getStatus());
        userDTO.setOrgId(organizationDTO.getOrgId());
        List<UserDTO> userDTOList = userService.selectList(userDTO).getData();
        if (CollectionUtils.isNotEmpty(userDTOList)) {
            for (UserDTO user : userDTOList) {
                growingIOService.uploadGrowingio(user, organizationDTO, packageDTO);
            }
            if (log.isInfoEnabled()) {
                log.info("[USER] org_id:{} user上传结束，数量：{}", organizationDTO.getOrgId(), userDTOList.size());
            }
        }
        return ServiceResult.success();
    }

    @Override
    public ServiceResult<List<UserDTO>> findFreeUserByUsername(String username) {
        // 校验参数
        if (StringUtils.isBlank(username)) {
            return ServiceResult.success();
        }
        List<UserDTO> existUser = new ArrayList<>();

        // 通过邮箱查询用户
        UserDTO userQueryByEmail = new UserDTO();
        userQueryByEmail.setStatus(UserStatusEnum.ACTIVATED.getStatus());
        userQueryByEmail.setEmail(username.toLowerCase());
        List<UserDTO> existUsersByEmail = userService.listByCondition(userQueryByEmail).getData();
        if (CollectionUtils.isNotEmpty(existUsersByEmail)) {
            existUser.addAll(existUsersByEmail);
        }

        // 通过用户名查询用户
        UserDTO userQueryByUsername = new UserDTO();
        userQueryByEmail.setStatus(UserStatusEnum.ACTIVATED.getStatus());
        userQueryByUsername.setUserName(username);
        userQueryByUsername.setEdition(UserEditionEnum.FREE.getType());
        List<UserDTO> existUsersByUsername = userService.listByCondition(userQueryByUsername).getData();
        if (CollectionUtils.isNotEmpty(existUsersByEmail)) {
            existUser.addAll(existUsersByUsername);
        }

        // 设置返回值, 用户的结果集去重
        return ServiceResult.success(existUser.stream().distinct().collect(Collectors.toList()));
    }

    /**
     * 校验参数-校验用户是否有特定角色
     *
     * @param userId
     * @param orgId
     * @return ServiceResult<String>
     * @author wangyunyun <yunyun.wang@idiaoyan.com>
     * @version v1.0
     * @date 2022/3/14 14:45
     */
    private ServiceResult<String> checkParamByCheckRole(String userId, String orgId) {
        // 校验参数
        if (StringUtils.isBlank(userId)) {
            return ServiceResult.fail(ReqErrorCodeEnum.PARAM_LOST, "userId cannot be blank");
        }
        // 如果公司id为null, 则查询用户信息
        if (StringUtils.isBlank(orgId)) {
            UserDTO userDto = userService.selectById(userId).getData();
            if (userDto == null) {
                return ServiceResult.fail(ResourceErrorCodeEnum.NOT_FOUND, String.format("user not exist. userId = %s", userId));
            }
            orgId = userDto.getOrgId();
        }

        return ServiceResult.success(orgId);
    }

    @Override
    public String getDisplayUserName(UserDTO userDTO) {
        if (StringUtils.isNotBlank(userDTO.getWxUnionid())) {
            return "微信昵称：" + userDTO.getUserName();
        } else if (StringUtils.isNotBlank(userDTO.getPhone())) {
            return "手机：" + userDTO.getPhone();
        } else {
            return userDTO.getUserName();
        }
    }

    @Override
    public ServiceResult<String> getDisplayUserNameByUserId(String userId) {
        // 校验参数
        if (!ObjectId.isValid(userId)) {
            return ServiceResult.fail(ReqErrorCodeEnum.PARAM_FORMAT, "id wrong");
        }
        // 查询用户信息
        ServiceResult<UserDTO> userRt = userService.getUserByPrimaryKey(userId);
        // 处理成功
        if (userRt.isSuccess() && userRt.getData() != null) {
            String displayUserName = this.getDisplayUserName(userRt.getData());
            return ServiceResult.success(displayUserName);
        }
        // 处理失败
        return ServiceResult.fail(ResourceErrorCodeEnum.NO_DATA, String.format("user not exist. id = %s", userId));
    }

    @Override
    public ServiceResult<GrowingioDTO> getUserProperty(UserDTO userDTO, OrganizationDTO organizationDTO, String packageNameOrId) {
        // 校验参数
        if (!ObjectId.isValid(userDTO.getUserId())) {
            return ServiceResult.fail(ReqErrorCodeEnum.PARAM_FORMAT, "id wrong");
        }
        if (StringUtils.isBlank(organizationDTO.getCode())) {
            return ServiceResult.fail(ReqErrorCodeEnum.PARAM_LOST, "org_code cannot blank");
        }
        if (organizationDTO.getInnerFlag() == null) {
            return ServiceResult.fail(ReqErrorCodeEnum.PARAM_LOST, "org_inner cannot blank");
        }
        if (ObjectId.isValid(packageNameOrId)) {
            // 如果是套餐id则查询套餐名称
            PackageDTO packageDTO = packageGrpcService.getById(packageNameOrId);
            packageNameOrId = packageDTO != null ? packageDTO.getName() : StringUtils.EMPTY;
        }
        // 设置返回值
        return ServiceResult.success(growingIOService.getUserProperty(userDTO, organizationDTO, packageNameOrId));
    }

    @Override
    public ServiceResult<List<UserDTO>> listUserByPhoneOrEmail(String username, boolean queryUsername, String orgId) {
        // 通过手机号查询用户
        UserDTO userDTOByPhone = new UserDTO();
        userDTOByPhone.setPhone(username);
        userDTOByPhone.setStatus(UserStatusEnum.ACTIVATED.getStatus());
        userDTOByPhone.setOrgId(StringUtils.isNotBlank(orgId) ? orgId : null);
        List<UserDTO> existUsersByPhone = userService.listByCondition(userDTOByPhone).getData();
        // 通过邮箱查询用户
        UserDTO userDTOByEmail = new UserDTO();
        userDTOByEmail.setEmail(username.toLowerCase());
        userDTOByEmail.setStatus(UserStatusEnum.ACTIVATED.getStatus());
        userDTOByEmail.setOrgId(StringUtils.isNotBlank(orgId) ? orgId : null);
        List<UserDTO> existUsersByEmail = userService.listByCondition(userDTOByEmail).getData();
        // 通过用户名查询用户
        List<UserDTO> existUsersByUsername = null;
        if (queryUsername) {
            UserDTO userDTOByUsername = new UserDTO();
            userDTOByUsername.setUserName(username);
            userDTOByUsername.setStatus(UserStatusEnum.ACTIVATED.getStatus());
            userDTOByUsername.setOrgId(StringUtils.isNotBlank(orgId) ? orgId : null);
            existUsersByUsername = userService.listByCondition(userDTOByUsername).getData();
        }
        // 设置返回值
        if (CollectionUtils.isEmpty(existUsersByPhone) && CollectionUtils.isEmpty(existUsersByUsername)) {
            return ServiceResult.success(existUsersByEmail);
        }
        if (CollectionUtils.isEmpty(existUsersByEmail) && CollectionUtils.isEmpty(existUsersByUsername)) {
            return ServiceResult.success(existUsersByPhone);
        }
        if (CollectionUtils.isEmpty(existUsersByEmail) && CollectionUtils.isEmpty(existUsersByPhone)) {
            return ServiceResult.success(existUsersByUsername);
        }

        // 用户的结果集去重
        existUsersByPhone.addAll(existUsersByEmail);
        if (CollectionUtils.isNotEmpty(existUsersByUsername)) {
            existUsersByPhone.addAll(existUsersByUsername);
        }
        return ServiceResult.success(existUsersByPhone.stream().collect(Collectors
                .collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(UserDTO::getUserId))), ArrayList::new)));
    }

    @Override
    public ServiceResult<List<UserDTO>> listUserByAuth(String username, String password, String orgCode) {
        // 校验参数
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            return ServiceResult.fail(null, "auth params lost.", String.valueOf(ReqErrorCodeEnum.PARAM_LOST.getCode()));
        }

        // 通过条件查询对应的用户
        List<UserDTO> userDTOList = new ArrayList<>();
        if (StringUtils.isNotBlank(orgCode)) {
            OrganizationDTO org = organizationService.selectByOrgCode(orgCode).getData();
            List<UserDTO> existUsers = this.listUserByPhoneOrEmail(username, true, Optional.ofNullable(org.getOrgId()).orElse(null)).getData();
            if (CollectionUtils.isNotEmpty(existUsers)) {
                UserDTO existUser = existUsers.get(0);
                ServiceResult<Void> checkPwdRt = PwdUtil.checkPasswordByBusiness(password, existUser.getPassword(), existUser.getSalt());
                if (!checkPwdRt.isSuccess()) {
                    return ServiceResult.fail(null, checkPwdRt.getMsg(), checkPwdRt.getErrorCode());
                }
                userDTOList.add(existUser);
            }
        } else {
            List<UserDTO> existUsers = this.listUserByPhoneOrEmail(username, false, null).getData();
            for (UserDTO existUser : existUsers) {
                boolean checkPwdRt = PwdUtil.checkPassword(password, existUser.getPassword(), existUser.getSalt());
                if (checkPwdRt) {
                    userDTOList.add(existUser);
                }
            }
        }

        // 设置返回值
        if (CollectionUtils.isEmpty(userDTOList)) {
            return ServiceResult.fail(AuthErrorCodeEnum.USER_NOT_EXISTS, "user not found.");
        }
        return ServiceResult.success(userDTOList);
    }


    @Override
    public ServiceResult<List<UserDTO>> listUsersByGroupIdAndRoleId(List<UserConditionGroupDTO> conditionDtoList) {
        Set<String> groupIdSet = new HashSet<>();
        Set<String> roleIdSet = new HashSet<>();
        if (CollectionUtils.isNotEmpty(conditionDtoList)) {
            for (UserConditionGroupDTO userConditionGroupDTO : conditionDtoList) {
                groupIdSet.add(userConditionGroupDTO.getGroupId());
                roleIdSet.add(userConditionGroupDTO.getRoleId());
            }
        }
        List<UserConditionGroupDO> userConditionGroupList = userAccountDao.listUsersByGroupIdAndRoleId(groupIdSet, roleIdSet);
        if (CollectionUtils.isEmpty(userConditionGroupList)) {
            return ServiceResult.success(new ArrayList<>());
        }
        Set<String> userIdSet = new HashSet<>();
        for (UserConditionGroupDO isDo : userConditionGroupList) {
            for (UserConditionGroupDTO isDto : conditionDtoList) {
                if (ObjectId.isValid(isDo.getGroupId()) && isDo.getGroupId().equals(isDto.getGroupId())
                        && ObjectId.isValid(isDo.getRoleId()) && isDo.getRoleId().equals(isDto.getRoleId())) {
                    userIdSet.add(isDo.getUserId());
                }
            }
        }
        return userService.selectByIds(new ArrayList<>(userIdSet));
    }

    @Override
    public ServiceResult<Integer> updateUser(UserDTO userDTO, boolean isSync) {
        ServiceResult<UserDTO> oldUserRst = userService.selectById(userDTO.getUserId());
        UserDTO oldUser = oldUserRst.getData();
        if (!oldUserRst.isSuccess() || Objects.isNull(oldUser)) {
            return ServiceResult.fail(AppResourceErrorCode.NOT_FOUND, "update_user user_id=[%s] failed. old_user not found.", userDTO.getUserId());
        }
        // 未激活的用户不允许修改状态
        if (!isSync && oldUser.getStatus().equals(UserStatusEnum.INACTIVATED.getStatus()) && !userDTO.getStatus().equals(oldUser.getStatus())) {
            return ServiceResult.fail(AppRequestErrorCode.PARAM_FORBIDDEN, "The status cannot be changed when the user is not activated");
        }
        // 将用户状态改为未激活
        if (!oldUser.getStatus().equals(userDTO.getStatus()) &&
                userDTO.getStatus().equals(UserStatusEnum.INACTIVATED.getStatus())) {
            userService.updateById(userDTO);
            userService.updateUserConsumption(userDTO.getOrgId(), -1);
        } else if (!oldUser.getStatus().equals(userDTO.getStatus()) && UserStatusEnum.ACTIVATED.getStatus().equals(userDTO.getStatus())) {
            // 用户状态改为激活
            ServiceResult<Boolean> quotaResult = userService.checkUserQuota(userDTO.getOrgId(), 1);
            // 用户数已达上限
            if (!Boolean.TRUE.equals(quotaResult.getData())) {
                return ServiceResult.fail(quotaResult.getErrorData(), quotaResult.getMsg());
            }
            userService.updateById(userDTO);
            userService.updateUserConsumption(userDTO.getOrgId(), 1);
        } else {
            userService.updateById(userDTO);
        }
        return ServiceResult.success();
    }

    @Override
    public ServiceResult<Boolean> getLock(String orgId) {
        boolean lockFlag = userLockUtil.getLockFlag(orgId);
        return ServiceResult.success(lockFlag);
    }

}
